<template>
  <div class="apply_page">
    <van-nav-bar
      title="事项办理修改"
      left-arrow
      @click-left="$router.go(-1)"
      fixed
    />
    <div class="base_info">
      <p>申请人信息</p>
      <van-field
        v-model="form.username"
        label="姓名"
        placeholder="请输入姓名"
        clearable
        class="repair_input_box"
        required
      />
      <van-field
        v-model="form.idcardNo"
        label="身份证号"
        placeholder="请输入身份证号"
        clearable
        class="repair_input_box"
        required
      />
      <van-field
        v-model="form.contactPhone"
        type="number"
        label="手机号"
        placeholder="请输入手机号"
        clearable
        maxlength="15"
        class="repair_input_box"
        required
      />
    </div>
    <div class="devide_div"></div>
    <div class="base_info">
      <p>所需材料<span v-show="reason != null && reason != ''" class="content_desc" style="color:#ff0000;padding:0;border:none;font-size:12px;">({{reason}})</span></p>
      <div
        class="manage_content image_box"
        v-for="item in items"
        :key="item.id"
      >
        <div class="content_desc">{{ item.attachName }}
          <!-- <p class="content_desc" style="color:#ff0000;padding:0;border:none;font-size:12px;">{{reason}}</p> -->
        </div>
        <div
          v-for="(option, i) in item.currentImgList"
          :key="i"
          style="display:contents"
        >
          <div class="net_image" v-show="item.isShow">
            <img
              v-lazy="option" :key="option"
              @click="imagePreview(i, item.currentImgList)"
            />
            <svg-icon
              icon-class="关闭"
              class="icon_defined"
              @click.native.stop="deleteNetImage(option,i,item.id)"
            ></svg-icon>
          </div>
        </div>
        <van-uploader
          v-model="item.avatar"
          :max-count="Number(`${5 - item.attachUrl.split(',').length}`)"
          :name="item.attachName"
          class="img_upload_box"
          :before-read="beforeRead"
          :before-delete="beforeDelete"
          :after-read="afterRead"
        />
      </div>
    </div>
    <div class="devide_div"></div>
    <div class="base_info">
      <p>收件方式</p>
      <van-radio-group v-model="form.receiveType" class="radio_group_box">
        <van-radio icon-size="24px" name="1" checked-color="#DC4630"
          ><span
            :style="{ color: form.receiveType == '1' ? '#333333' : '#999999' }"
            >自取</span
          ></van-radio
        >
        <van-radio
          icon-size="24px"
          name="2"
          checked-color="#DC4630"
          style="margin-top:30px"
          ><span
            :style="{ color: form.receiveType == '2' ? '#333333' : '#999999' }"
            >EMS邮政（快递费为到付）</span
          ></van-radio
        >
      </van-radio-group>
      <van-field
        v-if="form.receiveType == '2'"
        v-model="form.receiveAddress"
        label="收件地址"
        placeholder="请输入收件地址"
        clearable
        class="repair_input_box"
        required
      />
    </div>
    <van-button
      :disabled="!disabled"
      class="next_btn apply_btn"
      @click="contact()"
      >修 改</van-button
    >
    <van-popup v-model="showLoading">
      <van-loading color="#DC4630" />
    </van-popup>
  </div>
</template>

<script>
import api from "@/controller/govService.js";
import constant from "@/controller/constant.js";
import { notEmpty } from "../../../emptyTest";
import uploadService from "@/controller/mine.js";
import util from "@/controller/Common/util.js";
import { ImagePreview } from "vant";
export default {
  data() {
    return {
      form: {
        username: "",
        idcardNo: "",
        contactPhone: "",
        applyInfos: [],
        receiveType: "1",
        receiveAddress: ''
      },
      reason: '',
      showLoading: false,
      items: []
    };
  },
  computed: {
    disabled: function() {
      return (
        notEmpty(this.form.username) &&
        notEmpty(this.form.idcardNo) &&
        notEmpty(this.form.contactPhone)
      );
    }
  },
  mounted() {
    this.getDetails(this.$route.query.id);
  },
  methods: {
    imagePreview(index, images) {
      ImagePreview({
        images: images,
        startPosition: index
      });
    },
    deleteNetImage(val,index,id) {
      for (let i = 0; i < this.items.length; i++) {
        let e = this.items[i];
        if (e.id == id) {
          e.currentImgList.splice(index,1);
        }
        if (e.currentImgList.length < 1) {
          e.isShow = false;
        }
      }
      this.$forceUpdate()
    },
    getDetails(id) {
      api.service_apply_v1_find(id).then(res => {
        if (res.code === "0") {
          this.form = res.datas;
          this.reason = res.datas.reason
          this.form.receiveType = this.form.receiveType + "";
          this.items = this.form.applyInfos;
          this.items.forEach(e => {
            e.isShow = true;
            if (e.attachUrl.split(",").length > 1) {
              e.currentImgList = e.attachUrl.split(",");
            } else {
              e.currentImgList = [e.attachUrl];
            }
          });
        } else {
          if (res && res.msg) {
            this.$toast(res.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      });
    },
    contact() {
      if (!util.validatePhoneNum(this.form.contactPhone)) {
        this.$toast("请输入合法手机号");
        return;
      }
      if (!util.validateIdCardNumber(this.form.idcardNo)) {
        this.$toast("请输入合法身份证号");
        return;
      }
      if (this.form.receiveType === '2'||this.form.receiveType === 2) {
        if (!notEmpty(this.form.receiveAddress)) {
          this.$toast("请输入地址");
          return;
        }
      }
      this.showLoading = true;
      let updateInfos = [];
      this.items.forEach(e => {
        if (e.imgList) {
          updateInfos.push({
            attachName: e.attachName,
            attachUrl: e.currentImgList.length > 0
              ? e.currentImgList.toString() + "," + e.imgList.toString()
              : e.imgList.toString()
          });
        } else {
          updateInfos.push({
            attachName: e.attachName,
            attachUrl: e.currentImgList.length > 0 ? e.currentImgList.toString() : ""
          });
        }
      });
      const data = {
        username: this.form.username,
        idcardNo: this.form.idcardNo,
        contactPhone: this.form.contactPhone,
        serviceId: this.$route.query.serviceId,
        receiveType: Number(this.form.receiveType),
        applyInfos: updateInfos,
        id: this.$route.query.id,
        address: this.form.receiveType === '2'?this.form.address:''
      };
      api
        .service_v1_update(data)
        .then(res => {
          if (res.code === "0") {
            this.$toast("修改成功");
            this.$router.go(-2);
          } else {
            if (res && res.msg) {
              this.$toast(res.msg);
            } else {
              this.$toast(constant.unusualMsg);
            }
          }
        })
        .catch(() => {})
        .then(() => {
          this.showLoading = false;
        });
    },
    downloadFile() {
      this.$toast("下载成功");
    },
    beforeDelete(file) {
      const lastModifyTime = file.file.lastModified;
      let arr = this.items;
      let deleteIndex = null;
      for (let i = 0; i < arr.length; i++) {
        const e = arr[i];
        if (e.avatar) {
          for (let j = 0; j < e.avatar.length; j++) {
            const ele = e.avatar[j];
            if (lastModifyTime == ele.file.lastModified) {
              deleteIndex = j;
            }
          }
        }
      }
      this.$nextTick(() => {
        for (let index = 0; index < arr.length; index++) {
          let element = arr[index];
          if (deleteIndex || deleteIndex === 0) {
            if (element.imgList) {
              element.imgList.splice(deleteIndex, 1);
            }
          }
        }
      });
      return true;
    },
    beforeRead(file) {
      const acceptImgs = ["image/jpeg", "image/png", "image/jpg"];
      if (!acceptImgs.includes(file.type)) {
        this.$toast("请上传JPG或者PNG格式的图片!");
        return false;
      }
      this.showLoading = true;
      return true;
    },
    afterRead(file, detail) {
      let formData = new FormData();
      formData.append("file", file.file);
      let i = this.items.findIndex(e => e.attachName === detail.name);
      uploadService
        .upload_image(formData)
        .then(res => {
          if (res.data.code === "0") {
            this.$toast("图片上传成功！");
            if (this.items[i].imgList) {
              this.items[i].imgList.push(res.data.datas);
            } else {
              this.items[i].imgList = [];
              this.items[i].imgList.push(res.data.datas);
            }
          } else {
            if (res && res.data && res.data.msg) {
              this.$toast(res.data.msg);
            } else {
              this.$toast(constant.unusualMsg);
            }
          }
        })
        .catch(() => {})
        .then(() => {
          this.showLoading = false;
          return true;
        });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../../../styles/workstation.scss";

.apply_page {
  background: #ffffff;
  height: 100%;
  position: relative;

  .net_image {
    position: relative;
    .icon_defined {
      position: absolute;
      z-index: 200;
      right: -8px;
      top: -8px;
      font-size: 18px;
      color: #999999;
    }
  }

  .manage_content {
    display: flex;
    flex-wrap: wrap;
    padding: 0 15px;
    background: #ffffff;

    span {
      font-size: 14px;
      color: #333333;
      line-height: 20px;
      padding: 14.5px 0 10px 0;
      width: 100%;
    }

    img {
      border-radius: 4.25px;
      width: 2.13333rem;
      height: 1.73333rem;
    }

    img:nth-child(3n + 1) {
      margin-left: 7.5px;
    }

    img:nth-child(3n + 3) {
      margin-left: 7.5px;
    }

    img:nth-child(n + 5) {
      margin-top: 7.5px;
    }

    li {
      padding: 14.5px 0;
      width: 100%;
      border-bottom: 1px solid #edeff2;
      font-size: 14px;
      color: #333333;
      line-height: 20px;
    }

    li:first-child {
      padding-top: 20px;
    }
    li:last-child {
      border: none;
    }

    .content_key {
      width: 106px;
      float: left;
    }

    .content_text {
      width: 239px;
      float: right;
      text-align: right;
    }
  }

  .base_info {
    p {
      font-size: 18px;
      color: #333333;
      line-height: 25px;
      padding: 10px 15px;
      border-bottom: 1px solid rgba(226, 226, 226, 0.5);
    }

    .radio_group_box {
      padding: 15px;
      border-bottom: 1px solid rgba(226, 226, 226, 0.5);
    }
  }

  .image_box {
    padding: 10px 15px 0;
    border-bottom: 1px solid rgba(226, 226, 226, 0.5);

    .content_desc {
      line-height: 20px;
      font-size: 14px;
      color: #333333;
      width: 70px;
      word-break: break-all;
      float: left;

      .download_btn {
        background: rgba(220, 70, 48, 0.1);
        border-radius: 2px;
        font-size: 10px;
        color: #dc4630;
        text-align: center;
        line-height: 14px;
        padding: 2px 8.5px;
      }
    }

    .img_upload_box {
      float: right;
    }
  }

  .image_box::after {
    content: "\20";
    display: block;
    height: 0;
    clear: both;
  }

  .image_box::before {
    position: absolute;
    left: 0.21333rem;
    color: #f44;
    font-size: 0.37333rem;
    content: "*";
  }

  .van-popup {
    background-color: #ffffff00;
  }
}
</style>

<style lang="scss">
.apply_page {
  .van-field__control {
    text-align: right;
    font-size: 14px;
  }

  .repair_input_box {
    .van-field__control {
      margin-right: 24px;
    }
  }

  .image_box {
    .van-uploader__preview-image {
      width: 80px;
      height: 65px;

      .van-image__error,
      .van-image__img,
      .van-image__loading {
        border-radius: 5px;
      }
    }

    .van-uploader__upload {
      width: 80px;
      height: 65px;
      border-radius: 5px;
      border-style: solid;
      background-color: #f5f7fa;
    }

    .van-uploader__upload-icon {
      font-size: 25px;
    }
  }
}
</style>
